<template>
    <main-layout :showHome="!isFromList" :showBack="isFromList" :title="`${isEdit ? '修改' : '新增'}项目`">
        <!-- 如果表单没有出现错误，那么会触发submit事件回调 -->
        <div class="form-box">
            <van-form @submit="onSubmit">
                <div class="title">基本信息</div>
                <van-field v-model="pageData.name"
                    label="项目名"
                    placeholder="输入项目名"
                    :rules="[{ required: true, message: '请填写项目名' }]"/>
                <!-- rules是定义当前表单的一个校验规则，它接收的是一个数组(因为会存在多个校验问题)，required是必填校验 -->
                <van-field v-model="pageData.signTime"
                    label="签订日期"
                    placeholder="选择签订日期"
                    readonly
                    :rules="[{ required: true, message: '选择签订日期' }]">
                    <!-- <template v-slot:button> -->
                    <template #button>
                        <van-button size="small" type="primary" color="#ff5b02" @click="timeShow = true" native-type="button">选择日期</van-button>
                    </template>
                </van-field>
                <van-field v-model="cityName"
                    label="地市"
                    placeholder="选择地市"
                    readonly
                    :rules="[{ required: true, message: '选择地市' }]">
                    <!-- <template v-slot:button> -->
                    <template #button>
                        <van-button size="small" type="primary" color="#ff5b02" @click="areaShow = true" native-type="button">选择地市</van-button>
                    </template>
                </van-field>
                <van-field v-model="pageData.address"
                    label="详细地址"
                    placeholder="输入详细地址"
                    :rules="[{ required: true, message: '输入详细地址' }]"/>
                <van-field v-model="pageData.liableName"
                    label="负责人"
                    placeholder="选择负责人"
                    readonly
                    :rules="[{ required: true, message: '选择负责人' }]">
                    <!-- <template v-slot:button> -->
                    <template #button>
                        <van-button size="small" type="primary" color="#ff5b02" @click="pickPerson()" native-type="button">选择负责人</van-button>
                    </template>
                </van-field>

                <div class="title">业主信息</div>
                <van-field v-model="pageData.ownerName"
                    label="业主"
                    placeholder="输入业主"
                    :rules="[{ required: true, message: '输入业主' }]"/>
                <van-field v-model="pageData.ownerAddress"
                    label="业主地址"
                    placeholder="输入业主地址"
                    :rules="[{ required: true, message: '输入业主地址' }]"/>
                <van-field v-model="pageData.ownerPhone"
                    label="联系电话"
                    placeholder="输入联系电话"
                    :rules="[
                        { required: true, message: '输入联系电话' },
                        { validator, message: '输入正确的手机号' }
                    ]"/>
                    <!-- { pattern: /^1[3-9]{1}[0-9]{9}$/, message: '输入正确的手机号', trigger: 'onBlur' } -->
                
                <div class="title">备注信息</div>
                <van-field v-model="pageData.remark"
                    label="备注"
                    placeholder="输入备注"/>
                <div style="margin: 12px 0;">
                    <!-- 在表单中使用native-type来指定按钮的具体功能,submit是提交表单的意思 -->
                    <van-button block type="info" native-type="submit" color="#ff5b02">提交</van-button>
                </div>
            </van-form>

            <!-- 这个组件,仅仅是一个日期组件,没有弹出功能 -->
            <van-popup v-model="timeShow"
                position="bottom"
                :close-on-click-overlay="false"
                :style="{ height: '308px' }">
                <van-datetime-picker v-model="signTime"
                    @cancel="timeShow = false"
                    @confirm="pickTime"
                    type="datetime"
                    title="选择年月日"/>
            </van-popup>

            <van-popup v-model="areaShow"
                position="bottom"
                :close-on-click-overlay="false"
                :style="{ height: '308px' }">
                <!-- 单独安装一个数据对象，因为地市数据不是很好找，cnpm i -S @vant/area-data -->
                <van-area title="选择地市"
                    @cancel="areaShow = false"
                    @confirm="pickArea"
                    :area-list="areaList"/>
            </van-popup>

            <van-popup v-model="personShow"
                position="right"
                :style="{ height: '100%', width: '80%' }">
                <div class="user-box">
                    <header>
                        <input type="text" v-model="personQuery.name" placeholder="输入用户姓名">
                        <button @click="pickPerson(true)">查询</button>
                    </header>
                    <ul @scroll="scrollEvt">
                        <li v-for="item in personList"
                            @click="pickUser(item)"
                            :key="item.id">
                            {{item.name}} {{item.dept}} {{item.duties}}
                        </li>
                        <li class="more">
                            {{
                                loading ? '加载中...' : hasMore ? '上滑加载更多' : '不要滑了，没有了'
                            }}
                        </li>
                    </ul>
                </div>
            </van-popup>
            
        </div>
    </main-layout>
</template>

<script>
    import { dateFormat } from '../../util'
    import { areaList } from '@vant/area-data'
import { personListApi, projectSaveApi } from '../../apis/projectApi'

    export default {
        data() {
            return {
                isFromList: false,
                isEdit: false,
                pageData: {
                    name: '',
                    liableId: '',
                    liableName: '',
                    signTime: '',
                    province: '',
                    city: '',
                    county: '',
                    address: '',
                    ownerId: '',
                    ownerName: '',
                    ownerAddress: '',
                    ownerPhone: '',
                    remark: ''
                },
                cityName: '',
                timeShow: false,
                signTime: new Date(),
                areaShow: false,
                areaList,
                personShow: false,
                personList: [],
                // 查询用户信息的查询对象
                personQuery: {
                    name: '',
                    page: 1,
                    size: 20
                },
                // 分页需要这样几个条件: 再加载数据的时候，不能进行下一页数据；一定要滚动到底部；后端还有数据没有获取回来
                loading: false,
                hasMore: true
            }
        },

        created() {
            this.isFromList = !!this.$route.query.from

            this.isEdit = !!this.$route.query.id
        },

        methods: {
            async onSubmit() {
                console.log('----------------------- submit method')
                console.log(this.pageData)

                let citys = this.cityName.split('/')
                this.pageData.province = citys[0]
                this.pageData.city = citys[1]
                this.pageData.county = citys[2]

                let result = await projectSaveApi(this.pageData)

                if (result.code === 200) {
                    this.$toast.success('保存成功')
                } else {
                    this.$toast.fail('保存失败')
                }
            },

            validator(val) {
                return /^1[3-9]{1}[0-9]{9}$/.test(val)
            },

            // 选择时间
            pickTime(val) {
                this.pageData.signTime = dateFormat(val, 'yyyy-MM-dd hh:mm:ss')
                this.timeShow = false
            },

            // 选择地市的确认回调
            pickArea(arr) {
                this.cityName = arr.reduce(function(res, item) {
                    res.push(item.name)
                    return res
                }, []).join('/')
                this.areaShow = false
            },

            // 打开选择负责人的弹出框
            pickPerson(isQuery) {
                // 需要把查询条件重置为空
                this.personQuery.page = 1
                this.personList = []

                // 加载状态开启
                this.loading = true

                // 发起数据请求
                this.getPersonList()
                // 在执行查询的时候不能调用
                if (!isQuery) {
                    this.personQuery.name = ''
                    this.personShow = true
                }
            },

            // getPersonList 获取用户数据的方法
            async getPersonList() {
                let result = await personListApi(this.personQuery)
                if (result.code === 200) {
                    this.personList = this.personList.concat(result.data.rows)

                    // 计算是否还有数据没有从后端获取回来: 当前页面 * 每一页数据 一定要小于 总数据
                    this.hasMore = this.personQuery.page * this.personQuery.size < result.data.total
                }

                // 因为vue是虚拟dom，而虚拟dom更新和赋值是异步，所以再关闭加载状态时，需要延迟
                setTimeout(() => {
                    this.loading = false
                })
            },

            // 滚动加载 -- 谁是容器(ul)，来注册滚动事件
            scrollEvt() {
                let target = window.event.target

                // 计算是否已经滚动到底部：容器展示高度 + 已经滚动上去的距离 === 容器的真实高度
                let isBottom = (target.clientHeight + target.scrollTop + 20) > target.scrollHeight

                // 因为要做请求节流(第一次请求没有结束的情况下，不能发起第二次请求)，必须有更多数据，一定要滚动到底部的时候才能执行加载
                if (!this.loading && this.hasMore && isBottom) {
                    // 开启节流阀门
                    this.loading = true

                    this.personQuery.page += 1
                    this.getPersonList()
                }
            },

            // 选择具体的负责人
            pickUser(user) {
                this.pageData.liableId = user.id
                this.pageData.liableName = user.name

                this.personShow = false
            }
        }
    }
</script>

<style lang="less" scoped>
    @import '../../style/common.less';

    .form-box {
        padding: 4px 12px;
        .title {
            display: block;
            font-size: .8rem;
            padding: 10px 0;
        }
    }

    .user-box {
        display: block;
        height: 100%;
        > header {
            display: flex;
            padding: 8px 12px;
            border-bottom: solid 1px @cdd;
            input {
                flex: 1;
                padding: 0;
                outline: none;
                border: none;
                font-size: .7rem;
                color: @c33;
                line-height: 32px;
            }
            button {
                flex: 0 0 68px;
                height: 32px;
                background-color: @primary;
                border: none;
                color: @cff;
                font-size: .7rem;
            }
        }

        > ul {
            display: block;
            padding: 8px 12px;
            height: calc(100% - 49px);
            overflow-x: hidden;
            li {
                border-bottom: solid 1px #ddd;
                font-size: .7rem;
                padding: 10px;
                &:last-child {
                    border-bottom: none;
                }
                &.more {
                    text-align: center;
                    color: @c99;
                }
            }
        }
    }
</style>